const router = require('koa-router')()
const db = require('../utils/database')

// 前缀
router.prefix('/questions')

router.get('/', async ctx => {
    const r = await db.doSQL('select * from exam where id > 30')
    console.log(r)
    ctx.body = 'exam' + JSON.stringify(r)
})

// 试题列表、分页、排序、查询
router.get('/exam-list', async ctx => {
    const { page = 0, pageSize = 20, sortBy, order = 'desc', query } = ctx.query
    let sql = `select * from questions`
    if (query) {
        sql += ` where name like '%${query}%'`
    }
    if (sortBy) {
        sql += ` order by ${sortBy} ${order}`
    }
    sql += ` limit ${page * pageSize},${pageSize}`
    const r = await db.doSQL(sql)
    const sqlTotal = 'select count(*) as total from questions'
    const rTotal = await db.doSQL(sqlTotal)
    const total = rTotal[0].total
    ctx.body = db.doResponse({ message: '试题列表', data: r, total: total })
})

// 删除
router.get('/delete-exam', async ctx => {
    const { id } = ctx.query
    const sql = 'delete from questions where id=?'
    const r = await db.doSQL(sql, [id])
    if (r.affectedRows > 0) {
        ctx.body = db.doResponse({ message: '删除试题成功', data: r })
    } else {
        ctx.body = db.doResponse({ success: false, errorCode: 5001, message: '删除试题失败', data: r })
    }
})

// 修改
router.post('/update-exam', async ctx => {
    const { id, cid, tips, title, answers, options, uid } = ctx.request.body
    const sql = 'update questions set cid=?,tips=?,title=?,answers=?,options=?,uid=? where id=?'
    const params = [id, cid, tips, title, answers, options, uid]
    const r = await db.doSQL(sql, params)
    if (r.affectedRows > 0) {
        ctx.body = db.doResponse({ message: '修改类别成功', data: r })
    } else {
        ctx.body = db.doResponse({ success: false, errorCode: 5001, message: '修改类别失败', data: r })
    }
})

// 新增试题 
router.post('/save-exam', async ctx => {
    const { cid, tips, title, answers, options, uid } = ctx.request.body
    const sql = 'insert into questions(cid, tips, title, answers, options, uid) values (?,?,?,?,?,?)'
    const params = [cid, tips, title, answers, options, uid]
    const r = await db.doSQL(sql, params)
    console.log(r)
    if (r.affectedRows > 0) {
        ctx.body = db.doResponse({ message: '新增试题成功', data: r })
    } else {
        ctx.body = db.doResponse({ success: false, errorCode: 5001, message: '新增试题失败', data: r })
    }
})


// 随机获取50道题
router.get('/rand-list', async ctx => {
    const { pageSize = 50 } = ctx.request.body
    const sql = `select id, title, options, tips, answers from questions order by rand() limit ${pageSize}`
    const r = await db.doSQL(sql, [pageSize])
    console.log(r)
    ctx.body = db.doResponse({ message: '随机50试题', data: r })
})




module.exports = router